request = require 'request'
svgCaptcha = require 'svg-captcha'
config = require '../../config'


Captcha =

  # 加载图形验证码
  getCaptcha: (req, res, next) ->
    captOpt =
      noise: 0
      color: true
      background: '#d4edf2'
      ignoreChars: '0o1iIlt'
    captcha = svgCaptcha.create captOpt
    req.session.captcha =  ("" + captcha.text).toLowerCase()
    console.log req.session.captcha
    res.set 'Content-Type', 'image/svg+xml'
    res.status(200).send captcha.data

  # 检查是否有图形验证码 captcha必填
  checkCaptcha: (req, res, next) ->
    _captcha = req.query?.captcha or req.params?.captcha or req.body?.captcha or null

    if !!_captcha
      _captcha = _captcha.toLowerCase()

    if null is _captcha
      return res.status(400).json {'error': '验证码必填！'}

    unless req.session?.captcha and _captcha is req.session?.captcha
      return res.status(400).json {'error': '验证码错误！'}
    req.session?.captcha = ''
    return next()

  # 检查图形验证码，如果有captcha参数则检查，没有则跳过，captcha非必填
  tryCheckCaptcha: (req, res, next) ->
    _captcha = req.query?.captcha or req.params?.captcha or req.body?.captcha or null

    if !!_captcha
      _captcha = _captcha.toLowerCase()

    if null is _captcha
      return next()

    unless req.session?.captcha and _captcha in [req.session.captcha]
      return res.status(400).json {'error': '验证码错误！'}

    return next()

module.exports = Captcha